﻿using System;
using System.ServiceModel.Channels;
using System.Transactions;

namespace Microsoft.Biztalk.Adapters.Wcf.NullBinding
{
    class NullRequestContext : RequestContext
    {
        private CommittableTransaction internalTransaction;
        private Message ReplyMessage { get; set; }
        private Message requestMessage;
        private bool logMessage;

        public NullRequestContext(CommittableTransaction transaction, Message requestMessage, bool logMessage)
        {
            this.logMessage = logMessage;
            this.requestMessage = requestMessage;
            this.internalTransaction = transaction;
        }

        public override void Abort()
        {
        }

        public override IAsyncResult BeginReply(Message message, TimeSpan timeout, AsyncCallback callback, object state)
        {
            this.ReplyMessage = message;
            return new NullAsyncResult(callback, state);
        }

        public override IAsyncResult BeginReply(Message message, AsyncCallback callback, object state)
        {
            this.ReplyMessage = message;
            return new NullAsyncResult(callback, state);
        }

        public override void Close(TimeSpan timeout)
        {
        }

        public override void Close()
        {
        }

        public override void EndReply(IAsyncResult result)
        {
            Reply(this.ReplyMessage);
        }

        public override void Reply(Message message, TimeSpan timeout)
        {
            Reply(message);
        }

        public override void Reply(Message message)
        {
            Helpers.LogReceivedMessage(message, this.logMessage,MessageType.Reply);
            if (this.internalTransaction != null && this.internalTransaction.TransactionInformation.Status == TransactionStatus.Active)
            {
                if (!message.IsFault)
                {
                    this.internalTransaction.Commit();
                }
                else
                    this.internalTransaction.Rollback();
            }
        }

        public override Message RequestMessage
        {
            get { return this.requestMessage; }
        }
    }
}
